import React from 'react';
import { Drawer, Form, Input, Button, Radio, message, InputNumber, Cascader } from 'antd';
import { FormInstance } from 'antd/lib/form';

import { LineCity, ResourcePoolInfo } from '../../../../schema/ResourcePool';
import {
  createResourcePool,
  getLineCitysList,
  modifyResourcePool,
} from '../../../../servers/servers';
import { checkStr, verifyNull } from '../../../../../utils/tools';
/**
 * 资源池props
 */
interface IProps {
  /**提交函数结束后的回调,编辑需要传obj，判断是否跳第一页 */
  callback: (obj?: any) => any;
}

/**
 * 资源池state
 */
interface IState {
  // 当前的操作类型为新增还是编辑
  mode: 'create' | 'modify';
  // 当前操作弹出抽屉的可见性
  visible: boolean;
  // 地市列表
  cityOptions: LineCity[];
}

/**
 * 资源池管理操作
 */
export class ResourcePoolOperationDrawer extends React.Component<IProps, IState> {
  // 表单引用
  private formRef: React.RefObject<FormInstance>;

  // 当前的资源池信息
  private resourcePoolInfo?: ResourcePoolInfo;

  constructor(props: IProps) {
    super(props);
    this.formRef = React.createRef<FormInstance>();
    this.state = {
      ...props,
      mode: 'create',
      visible: false,
      cityOptions: [],
    };
  }

  /**
   * 展开抽屉并设置类型
   */
  public open(mode: 'create' | 'modify', record?: ResourcePoolInfo): void {
    this.initLineCitys();
    this.setState(
      {
        visible: true,
        mode: mode,
      },
      () => {
        if (mode === 'modify') {
          // 测试全选-回显
          // if (record) {
          //   record.lineCities = null as any;
          // }
          this.resourcePoolInfo = record;
          this.formRef.current?.setFieldsValue(record);
        }
      }
    );
  }

  /**
   * 关闭抽屉
   */
  public close(): void {
    this.formRef.current?.resetFields();
    this.setState({
      visible: false,
    });
  }

  /**获取地市列表 */
  private async initLineCitys() {
    try {
      const { data } = await getLineCitysList();
      this.setState({
        cityOptions: data,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }

  /**城市选择 */
  private onCityChange = (value: any, selectedOptions: any) => {
    console.log('地市选择>', value, 'options：', selectedOptions);
  };

  /**城市过滤*/
  private cityFilter = (inputValue: string, path: any[]) => {
    return path.some(option => option.name?.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
  };

  /**
   * 提交 新增/编辑 的数据
   */
  private submitData(): void {
    const form = this.formRef.current;
    form?.validateFields().then(res => {
      const val = form.getFieldsValue() as ResourcePoolInfo;
      // val.lineCities = JSON.stringify(val.lineCities) as any;
      if (this.state.mode === 'create') {
        createResourcePool(val)
          .then(res => {
            if (res.code === 0) {
              message.success('创建成功');
              this.close();
              this.props.callback();
            } else {
              message.error(`${res.tips}(错误码: ${res.code})`);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        const resourceId = this.resourcePoolInfo?.resourceId as number;
        modifyResourcePool(resourceId, val)
          .then(res => {
            if (res.code === 0) {
              message.success('编辑成功');
              this.close();
              this.props.callback(resourceId);
            } else {
              message.error(`${res.tips}(错误码: ${res.code})`);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  }

  /**
   * 渲染抽屉底部footer
   */
  private buildFooter(): JSX.Element {
    return (
      <div className="drawer-footer-buttongroup">
        <Button
          type="primary"
          onClick={() => {
            this.submitData();
          }}
        >
          确定
        </Button>
        <Button
          onClick={() => {
            this.close();
          }}
        >
          取消
        </Button>
      </div>
    );
  }

  render() {
    const { visible, mode, cityOptions } = this.state;

    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };

    const validateStr = (_: any, value: string) => {
      return checkStr(value) ? Promise.resolve() : Promise.reject('请输入英文数字下划线');
    };

    return (
      <>
        <Drawer
          width={500}
          visible={visible}
          onClose={() => {
            this.close();
          }}
          title={mode === 'create' ? '新建资源池' : '编辑资源池'}
          footer={this.buildFooter()}
        >
          <Form {...layout} layout="horizontal" ref={this.formRef} initialValues={{ type: 'VOIP' }}>
            <Form.Item
              label="资源池名称"
              name="resourceName"
              rules={verifyNull('请输入资源池名称')}
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <Input placeholder="请输入资源池名称" maxLength={30} />
            </Form.Item>
            <Form.Item label="类别" name="type" rules={verifyNull('请选择类别')}>
              <Radio.Group
                onChange={e => {
                  // 清空form选择
                  this.formRef.current?.resetFields(['location', 'number']);
                }}
              >
                <Radio value="VOIP">VOIP</Radio>
                <Radio value="GOIP">GOIP</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, curValues) => prevValues.type !== curValues.type}
            >
              {({ getFieldValue }) => {
                return (
                  getFieldValue('type') === 'VOIP' && (
                    <>
                      <Form.Item
                        label="资源池地址"
                        name="location"
                        rules={[{ required: true, message: '请输入资源池地址' }]}
                      >
                        <Input placeholder="请输入资源池地址" maxLength={100} />
                      </Form.Item>
                      <Form.Item
                        label="资源总数"
                        name="number"
                        rules={[{ required: true, message: '请输入资源总数' }]}
                      >
                        <InputNumber
                          className="input-number"
                          min={1}
                          max={99999999}
                          precision={0}
                          placeholder="请输入资源总数"
                        />
                      </Form.Item>
                    </>
                  )
                );
              }}
            </Form.Item>
            <Form.Item label="资源描述" name="resourceDesc">
              <Input placeholder="请输入资源描述" maxLength={30} />
            </Form.Item>
            <Form.Item label="主叫前缀" name="callingPrefix">
              <Input placeholder="请输入主叫前缀" maxLength={30} />
            </Form.Item>
            <Form.Item label="被叫前缀" name="calledPrefix">
              <Input placeholder="请输入被叫前缀" maxLength={30} />
            </Form.Item>
            <Form.Item label="线路地市" name="lineCities">
              <Cascader
                multiple
                fieldNames={{ label: 'name', value: 'id', children: 'cities' }}
                options={cityOptions as any}
                onChange={this.onCityChange}
                placeholder="请选择线路地市"
                showSearch={{ filter: this.cityFilter }}
                allowClear
              />
            </Form.Item>
            <Form.Item
              label="账号"
              name="accountNumber"
              rules={[
                {
                  validator: validateStr,
                },
              ]}
            >
              <Input placeholder="请输入账号" maxLength={15} />
            </Form.Item>
            <Form.Item
              label="密码"
              name="passWord"
              rules={[
                {
                  validator: validateStr,
                },
              ]}
            >
              <Input placeholder="请输入密码" maxLength={15} />
            </Form.Item>
          </Form>
        </Drawer>
      </>
    );
  }
}
